/*
write by wuweiwei
www.github.com/flybirdsoft
www.flybirdsoft.com/wui
 */

var TreeGrid = function(options){
	/*
	options = {
		container:dom,
		columns:[
			{
				field:"",
				title:""
				width:"100px",
				text : "" ,    自定义列的单元格文字
				formatter:function(object){
					object.col
					object.data
					object.rows
					object.row
					object.index
				}
			}
		],
		//columns:['col1','col2']
		width:"100px",
		colWidth:"100px",
		useIcon : false,
		onAjaxLoad:function(object){
			object.node ,
			object.item ,
			object.index,
			object.data ,
			object.level
		},
		onRowClick : function(e){
			this.row is current tr
		},
		onCellClick : function(e){
			this.cell is td
		}
	}
	 */
	this.options = options;
	this.options.container.style.position="relative";
	this.tplTable = '<table class="treeGrid" cellspacing="0" cellpadding="0" border="0" style="border-collapse:collapse">\
						<thead class="treeGrid-grop" style="display:table-row-group;">{headers}</thead>\
						<tbody class="treeGrid-rows" style="display:table-row-group;">{rows}</tbody>\
					</table>';
	this.tplHeader = '<tr class="treeGrid-header">{headers}</tr>';
	this.tplHeaderCol = '<th class="treeGrid-header-col" style="width:{width}" colspan="{colspan}" rowspan="{rowspan}" style="{style}">{col}</th>';
	this.tplRow = '<tr class="treeGrid-row {treeGrid-row-n}" index={index} level="{level}">{cols}</tr>';
	this.tplCol = '<td field="{field}" class="treeGrid-col {treeGrid-col-n}" style="width:{width}"><div class="treeGrid-col-content">{text}</div></td>';
	this.cacheColWidth = []; /*存储 options 里 设置的宽度信息,用来控制列宽(td)*/
	this.dynamicColWidth = []; /*计算table生产后td的宽度,用于设置表格树的td宽度*/
	this.tplExtend = '<i state="extended" isloaded="false" class="{class}" style="font-style:normal;cursor:pointer;">{+}</i>';
	/*this.tplExtend attr state = "closed|extended" ; isloaded="true",表示此节点已经加载了数据,通过js控制 */
	this.cacheData = {};

	this.isLoaded = true; /*此方法暴露给开发者,暴露给 onAjaxLoad :function(){this.isLoaded}*/

	this.node_TableContainer = document.createElement("div");
	this.node_TableContainer.className = "treeGrid-container";
	this.options.container.appendChild(this.node_TableContainer);

	this.initMask();

	this.loadData(options.data);
	this.bindEvent();

	/*外部可调用变量*/
	this.loadingTimeout = 100;

}
TreeGrid.prototype.initMask = function(){
	this.node_Mask = document.createElement("div");
	this.node_Mask.className = "treeGrid-mask";
	this.node_Mask.style.display = "none";
	this.options.container.appendChild(this.node_Mask);
};
TreeGrid.prototype.hideMask = function(){
	this.node_Mask.style.display = "block";
}
TreeGrid.prototype.showMask = function(){
	var th = this;
	setTimeout(function(){
		th.node_Mask.style.display = "none";
	},this.loadingTimeout);
	
}

/*
功能:判断是否是多表头,是多表头返回两个表头的列信息
*/
TreeGrid.prototype.getDoubleColumns = function(columns){
	/*
	columns is TreeGrid's options.columns
	columns is array
	*/
	var i,j;
	var len = columns.length;
	var subLen,children;
	var colA = [] , colB = []; /*colA si up columns , colB is down columns*/
	var isDoubleCol = false;

	for(i=0;i<len;i++)
	{
		if(columns[i].children!=undefined&&columns[i].children.length>0)/*有双表头*/
		{
			isDoubleCol = true;
			subLen = columns[i].children.length;
			children = columns[i].children;
			for(j=0;j<subLen;j++)
			{
				colB.push(children[j]);
			}
		}
		else
		{
			columns[i].isRowSpan = true; /*true 表示行合并*/
			colB.push(columns[i]);
		}
		colA.push(columns[i]);
	}

	//console.log("colA:",colA);
	//console.log("colB:",colB);

	return {
		colA : colA,
		colB : colB,
		isDoubleCol : isDoubleCol
	}
}

/*
生成表头
*/
TreeGrid.prototype.createColumns = function(options){
	/*
	options = {
		clen : n,
		tplHeaderCol : tplHeaderCol,
		columns : columns,
		updown : "up|down",
		isDoubleCol : true|false
	}
	*/
	var tplHeaderCol;
	var columns = options.columns;
	var col,colObj = {
		isObj : false
	};
	var _colWidth;
	var cacheColWidth = [];    /*存错表头计算好的列宽*/
	this.cacheColWidth = cacheColWidth;
	var defaultColWidth = "";
	var width = this.options.width;
	var isHaveWidth;
	var tplHeaderCols = '';
	clen = options.clen;

	for(ci=0;ci<clen;ci++)
	{
		tplHeaderCol = options.tplHeaderCol;
		col = columns[ci];

		/*如果是多表头,行合并的时候,下表头不产生列*/
		if(options.updown=="down" && col.isRowSpan && options.isDoubleCol)
		{
			continue;
		}

		if(typeof(col)!="string")
		{
			colObj.field = col.title || col.field;
			colObj.width = col.width||this.options.colWidth;
			colObj.isObj = true;
		}
		else
		{
			colObj.field = col;
			colObj.width = this.options.colWidth;
			colObj.isObj = false;
		}

		if(colObj.width!=undefined)
		{
			isHaveWidth = true;
			tplHeaderCol = tplHeaderCol.replace("{width}",colObj.width);
			_colWidth = colObj.width;
		}
		else
		{
			tplHeaderCol = tplHeaderCol.replace("{width}",defaultColWidth);
			_colWidth = colObj.width;
		}

		if(width!=undefined && !isHaveWidth)
		{
			tplHeaderCol = tplHeaderCol.replace("{width}",(parseInt(width.replace("px",""))/clen)+"px" );
			_colWidth = colObj.width;
		}
		else if(width==undefined && !isHaveWidth)
		{
			tplHeaderCol = tplHeaderCol.replace("{width}",(100/clen-0.2)+"%" );
			_colWidth = colObj.width;
		}

		cacheColWidth.push(_colWidth);
		if(_colWidth==undefined)
		{
			tplHeaderCol = tplHeaderCol.replace("width:","");
		}
		tplHeaderCol = tplHeaderCol.replace("{col}",colObj.title || colObj.field);

		if(col.children!=undefined&&col.children.length>0)
		{
			tplHeaderCol = tplHeaderCol.replace("{colspan}",col.children.length);
		}
		if(options.updown=="up" && col.isRowSpan)
		{
			tplHeaderCol = tplHeaderCol.replace("{rowspan}",2);
		}

		tplHeaderCols = tplHeaderCols + tplHeaderCol;
	}
	return tplHeaderCols;

};

/*
type:内部和外部接口
 */
TreeGrid.prototype.loadData = function(dataList){
	if(dataList==undefined)
	{
		return;
	}
	if(this.options.data==undefined)
	{
		this.options.data = dataList;
	}
	var i,v,j,ci;
	var len = dataList.length;
	if(this.options.pageSize!=undefined&&this.options.pageSize<len)
	{
		len = this.options.pageSize;
	}
	var columnsObject ={} ;/*from this.getDoubleColumns()*/
	var columns;
	var clen ,clen0; /*表头列个数,clen0是上表头个数*/

	var col;         /*col is 存储options.columns[i]的字段名*/
	var formatter;   /*formatter is options.columns[i]里的formatter()函数,数据遍历用都这个回调函数*/
	var colValue ;   /*通过options.formatter()函数返回*/
	var tplCol = this.tplCol;
	var tplCols = '';
	var tplRow = this.tplRow;
	var tplRows = '';
	var tplHeader = this.tplHeader;
	var tplHeaders = '';
	var tplHeaderCol = this.tplHeaderCol;
	var tplHeaderCols = '',tplHeaderColsUp='';/*最后得到的表头列 <tr><td></td>...</tr>*/
	var width = this.options.width;
	var defaultColWidth = "";
	var isHaveWidth = false;   /*this.options.columns里至少有一个width参数值*/
	var cacheColWidth = [];    /*存错表头计算好的列宽*/

	this.cacheColWidth = cacheColWidth;
	var tplExtend = this.tplExtend;
	this.extendIcon;
	var useIcon = this.options.useIcon;
	var span,tplSpan = '<span class="treeGrid-col-text">{text}</span>'; /*表格第一列的元素模板*/

	/*if 获取表头信息*/
	columnsObject = this.getDoubleColumns(this.options.columns);
	if(columnsObject.isDoubleCol)
	{
		columns = columnsObject.colB;/*有多表头,把下面的表头存储到columns里,下面循环用到*/
		clen = columnsObject.colB.length;
	}
	else
	{
		columns = columnsObject.colA;
		clen = columnsObject.colA.length;
	}

	this.showMask();

	/*if 上表头*/
	if(columnsObject.isDoubleCol)/*isDoubleCol == ture 表示有双表头*/
	{
		tplHeaderColsUp = this.createColumns({
			clen : columnsObject.colA.length,
			columns : columnsObject.colA,
			tplHeaderCol : this.tplHeaderCol,
			updown : "up",
			isDoubleCol : columnsObject.isDoubleCol
		});
	}

	/*下表头*/
	tplHeaderCols = this.createColumns({
		clen : clen,
		columns : columns,
		tplHeaderCol : this.tplHeaderCol,
		updown : "down",
		isDoubleCol : columnsObject.isDoubleCol
	});

	tplHeaders = tplHeader.replace("{headers}",tplHeaderColsUp);
	tplHeaders += tplHeader.replace("{headers}",tplHeaderCols);


	/*每行的数据*/
	var isFiled = false; /*false=不是数据字段(那就是自定义列),true=是数据字段*/
	for(i=0;i<len;i++)
	{
		tplRow = this.tplRow;
		tplCols = '';
		for(j=0;j<clen;j++)
		{
			isFiled = false;
			tplCol = this.tplCol;
			col = (columns[j]);
			formatter = (columns[j].formatter);

			if(typeof(col)!="string")
			{
				col = col.field;
			}
			for(v in dataList[i])
			{
				if(v==col)
				{
					isFiled = true;
					var item = dataList[i];
					if(cacheColWidth[j] != undefined)
					{
						tplCol = tplCol.replace("{width}" , cacheColWidth[j]);
					}
					else
					{
						tplCol = tplCol.replace("width:{width}" , "");
					}

					if(!useIcon)/*是否使用折叠图标*/
					{
						tplExtend = this.tplExtend.replace("{+}","+");
					}
					else
					{
						tplExtend = this.tplExtend.replace("{+}","");/*使用折叠图标*/
					}
					tplExtend = tplExtend.replace("{class}","treeGrid-icon-closed"); /*折叠图标*/

					this.extendIcon = tplExtend; /*为动态添加树表格使用*/
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : item[v],
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue || item[v]);
					tplCol = tplCol.replace("{text}",j==0 ? tplExtend + span : span);
					tplCol = tplCol.replace("{field}",v);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;
				}
			}
			if(!isFiled) /*自定义列*/
			{
					if(cacheColWidth[j] != undefined)
					{
						tplCol = tplCol.replace("{width}" , cacheColWidth[j]);
					}
					else
					{
						tplCol = tplCol.replace("width:{width}" , "");
					}

					if(!useIcon)/*是否使用折叠图标*/
					{
						tplExtend = this.tplExtend.replace("{+}","+");
					}
					else
					{
						tplExtend = this.tplExtend.replace("{+}","");/*使用折叠图标*/
					}
					tplExtend = tplExtend.replace("{class}","treeGrid-icon-closed"); /*折叠图标*/

					this.extendIcon = tplExtend; /*为动态添加树表格使用*/
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : columns[j].text,
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue||columns[j].text||"");
					tplCol = tplCol.replace("{text}",j==0 ? tplExtend + span : span);
					tplCol = tplCol.replace("{field}",columns[j].field);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;
			}
		}

		tplRow = tplRow.replace("{cols}",tplCols).replace("{index}",i).replace("{level}",0);
		tplRow = tplRow.replace("{treeGrid-row-n}","treeGrid-row-" + i);
		tplRows = tplRows + tplRow;
	}

	var tplHeader = this.tplHeader;
	var tplTable = this.tplTable;
	tplTable = tplTable.replace("{headers}",tplHeaders);
	tplTable = tplTable.replace("{rows}",tplRows);
	this.node_TableContainer.innerHTML = tplTable;

	this.hideMask();
};

TreeGrid.prototype.bindEvent = function(){
	var th = this;
	$(this.options.container).on("click","i",function(e){
		if(!th.isLoaded)
		{
			return;
		}
		th.dom_curRow = this.parentNode.parentNode.parentNode;
		if(th.dom_curRow.getAttribute("isloaded")=="true")
		{
			if(th.dom_curRow.getAttribute("state")=="closed")
			{
				th.dom_curRow.nextSibling.style.display = "table-row";
				th.dom_curRow.setAttribute("state","extended");
				if(th.options.useIcon)
				{
					this.className = "treeGrid-icon-extended";
				}
				else
				{
					this.innerHTML = "-";
				}
			}
			else
			{
				th.dom_curRow.nextSibling.style.display = "none";
				th.dom_curRow.setAttribute("state","closed");
				if(th.options.useIcon)
				{
					this.className = "treeGrid-icon-closed";
				}
				else
				{
					this.innerHTML = "+";
				}
			}
			return;
		}

		Array.prototype.forEach.call(th.dom_curRow.childNodes, function(ele, index) {
			th.dynamicColWidth.push(ele.offsetWidth);
		});
		var index = th.dom_curRow.getAttribute("index");
		th.currentObject = {
			tr : th.dom_curRow,
			item : th.options.data[index],
			index: index,
			data : th.options.data,
			level: parseInt(th.dom_curRow.getAttribute("level"))
		};
		th.row = th.currentObject;

		th.options.onAjaxLoad && th.options.onAjaxLoad.call(th,th.row);
		th.onAjaxLoad && th.onAjaxLoad.call(th,th.row);

		if(th.options.useIcon)
		{
			this.className = "treeGrid-icon-extended";
		}
		else
		{
			this.innerHTML = "-";
		}
	});

	/*row click*/
	$(this.options.container).on("click",".treeGrid-row",function(e){
		e.target = e.srcElement || e.target;
		var index = this.getAttribute("index");
		var item ,data , parentNode , dataName;
		parentNode = this.parentNode;/*<tbody class="treeGrid-tree-rows">*/
		dataName = parentNode.parentNode.getAttribute("data-name");
		if(parentNode.className=="treeGrid-tree-rows")
		{
			item = th.cacheData[dataName][index];
			data = th.cacheData[dataName];
		}
		else
		{
			item = th.options.data[index];
			data = th.options.data;
		}
		th.currentObject = {
			tr: this,
			item : item,
			index: index,
			data : data,
			level: parseInt(this.getAttribute("level"))
		};
		
		th.row = th.currentObject; /*当前row*/
		th.dom_curRow = th.currentObject.tr; /*this.asyncLoadNextData()函数用到*/

		th.options.onRowClick && th.options.onRowClick.call(th,e,th.row);
		th.onRowClick && th.onRowClick.call(th,e,th.row);
	});

	/*cell click*/
	$(this.options.container).on("click","td",function(e){
		th.options.onCellClick && th.options.onCellClick.call(th,e,this);
		th.onCellClick && th.onCellClick.call(th,e,this);
	});
}

/*
type:对外接口
function:异步加载children数据
*/
TreeGrid.prototype.asyncLoadData = function(dataList , _dataName , async){
	/*
	dataList is array
	_dataName is child table attr data-name
	async is 是否异步, async==true异步,async==false同步,
	async 参数没有开发,用不上
	*/
	var dataName = _dataName;   /*缓存用户动态数据的名字*/
	var columns;
	var clen;
	var col;

	var tplRow = this.tplRow;
	var tplRows = '';
	var tplCol;
	var tplCols = '';
	var len , i,v;
	var colValue;
	var formatter;

	var item , indents='', indent='<span class="indent"></span>';
	var indentLen;
	var span,tplSpan = '<span class="treeGrid-col-text">{text}</span>'; /*表格第一列的元素模板*/

	if(dataList==undefined)
	{
		return;
	}

	columnsObject = this.getDoubleColumns(this.options.columns);
	if(columnsObject.isDoubleCol)
	{
		columns = columnsObject.colB;/*有多表头,把下面的表头存储到columns里,下面循环用到*/
		clen = columnsObject.colB.length;
	}
	else
	{
		columns = columnsObject.colA;
		clen = columnsObject.colA.length;
	}
	
	this.showMask();

	dataName = dataName != undefined ? dataName : "dataName"+((new Date()).getTime());
	this.cacheData[dataName] = dataList; /*缓存用户动态加载的数据*/

	indentLen = this.currentObject.level+1; /*缩进级别,level base on 0 ,from dom attribute*/
	len = dataList.length;

	for(i=0;i<indentLen;i++)
	{
		indents += indent;
	}
	
	var isFiled = false;
	for(i=0;i<len;i++)
	{
		tplRow = this.tplRow;
		tplCols = '';
		item = dataList[i];
		for(j=0;j<clen;j++)
		{
			isFiled = false;
			tplCol = this.tplCol;
			col = columns[j];
			formatter = (columns[j].formatter);
			if(typeof(col)!="string")
			{
				col = col.field;
			}
			for(v in item)
			{
				if(col == v)
				{
					isFiled = true;
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : item[v],
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue||item[v]);
					tplCol = tplCol.replace("{text}",j==0 ? indents + this.extendIcon + span : span);
					tplCol = tplCol.replace("{width}" , this.dynamicColWidth[j]+"px");
					tplCol = tplCol.replace("{field}",v);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;
				}
			}
			if(!isFiled)
			{
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : columns[j].text,
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue||columns[j].text||"");
					tplCol = tplCol.replace("{text}",j==0 ? indents + this.extendIcon + span : span);
					tplCol = tplCol.replace("{width}" , this.dynamicColWidth[j]+"px");
					tplCol = tplCol.replace("{field}",columns[j].field);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;				
			}
		}
		tplRow = tplRow.replace("{cols}",tplCols);
		tplRow = tplRow.replace("{index}",i);
		tplRow = tplRow.replace("{level}",indentLen);
		tplRow = tplRow.replace("{treeGrid-row-n}","treeGrid-row-"+i);
		tplRows = tplRows + tplRow;
	}


	var tplTable = '<table border="0" frame="void" data-name={data-name} rules="all" class="treeGrid-tree" cellspacing="0" cellpadding="0" border="0" style="border-collapse:collapse">\
						<tbody class="treeGrid-tree-rows" style="">{rows}</tbody>\
					</table>';

	tplTable = tplTable.replace("{rows}",tplRows);
	tplTable = tplTable.replace("{data-name}",dataName);

	var children = null,cell;
	cell = '<td class="treeGrid-col treeGrid-tree-col" colspan={n} border="0">{table}</td>';
	cell = cell.replace("{n}",clen);
	cell = cell.replace("{table}",tplTable);

	if(async!=undefined&&!async)/*async==true同步*/
	{
		return '<tr class="treeGrid-row-tree" style="display:table-row;">{td+Table}</tr>'.replace("{td+Table}",cell);
	}
	children = document.createElement("tr");
	children.className = "treeGrid-row-tree";
	children.style.display = "table-row";
	children.innerHTML = cell;

	var node = this.dom_curRow.nextSibling;
	if(node!=null)
	{
		node.parentNode.insertBefore(children,node);
	}
	else
	{
		this.dom_curRow.parentNode.appendChild(children);
	}
	
	this.currentObject.tr.setAttribute("isloaded","true");/*设置当前父节点已经加载了子节点*/
	this.hideMask();
};

/*
type:外部接口
function:获取缓存数据
*/
TreeGrid.prototype.getData = function(dataName){
	return this.cacheData[dataName];
}

/*
type:外部接口
function:本地搜索
*/
TreeGrid.prototype.localSearch = function(options){
	/*
	options is {
		field : "",
		value : ""
		css : {
			"background-color" : "#ccc"
		},
        formatter:function(trs){},
        isFuzzy:true
	}
	*/
	var th = this;
	var $table = $(this.options.container).find(".treeGrid");
	var $trs = $table.find("tr");
	var findCount = 0;  /*查找到的个数*/
	var isFuzzy = options.isFuzzy==undefined ? false : options.isFuzzy ? true : false;
	console.log(options.isFuzzy);

	var produce = function(object){
		var i;
		console.log(object.node);
		for(v in options.css)
		{
			$(object.node).css(v,options.css[v]);
		}
		if(object.node.className!="treeGrid-row-tree")
		{
			options.formatter && options.formatter.call(th,object.node);
		}
		for(i=0;i<object.children.length;i++)
		{
			object.children[i].style.display = "table-row";
		}
	}

	$trs.each(function(index){
		$tds = $(this).find("td");
		var i,len = $tds.length , condition , $td , v;
		var tableChilren = [] , isFind = false;
		var tr;
		if(this.className.indexOf("treeGrid-row-tree")>-1) /*含有table的tr*/
		{
			tr = this.parentNode.parentNode.parentNode.parentNode;
			if(tr.nodeName=="TR")
			{
				tableChilren.push(tr);
			}
			return;
		}

		for(i=0;i<len;i++)
		{
			$td = $($tds[i]);
			if(isFuzzy)/*模糊查找*/
			{
				condition = $td.attr("field")==options.field && $td.find(".treeGrid-col-text").html().indexOf(options.value)>-1;
			}
			else
			{
				condition = $td.attr("field")==options.field && $td.find(".treeGrid-col-text").html()==options.value;
			}
			
			if(condition)
			{
				produce({
					node : this,
					children : tableChilren
				});
			}
		}
	});
};

/*
type:外部接口
function:加载同级数据
*/
TreeGrid.prototype.asyncLoadNextData = function(dataList,_dataName){
	var dataName = _dataName; /*缓存用户动态数据的名字*/
	var columns ;
	var clen;
	var col;

	var tplRow = this.tplRow;
	var tplRows = '';
	var tplCol = this.tplRow;
	var tplCols = '';
	var len , i,v;
	var colValue;
	var formatter;

	var item , indents='', indent='<span class="indent"></span>';
	var indentLen;
	var span,tplSpan = '<span class="treeGrid-col-text">{text}</span>'; /*表格第一列的元素模板*/

	var tr;

	if(dataList==undefined)
	{
		return;
	}

	columnsObject = this.getDoubleColumns(this.options.columns);
	if(columnsObject.isDoubleCol)
	{
		columns = columnsObject.colB;/*有多表头,把下面的表头存储到columns里,下面循环用到*/
		clen = columnsObject.colB.length;
	}
	else
	{
		columns = columnsObject.colA;
		clen = columnsObject.colA.length;
	}

	this.showMask();

	dataName = dataName != undefined ? dataName : "dataName"+((new Date()).getTime());
	this.cacheData[dataName] = dataList; /*缓存用户动态加载的数据*/

	indentLen = this.currentObject.level; /*缩进级别,level base on 0 ,from dom attribute*/
	len = dataList.length;

	for(i=0;i<indentLen;i++)
	{
		indents += indent;
	}
	
	var isFiled = false;
	for(i=len-1;i>=0;i--)
	{
		tplRow = this.tplRow;
		tplCols = '';
		item = dataList[i];
		for(j=0;j<clen;j++)
		{
			isFiled = false;
			tplCol = this.tplCol;
			col = columns[j];
			formatter = (columns[j].formatter);
			if(typeof(col)!="string")
			{
				col = col.field;
			}
			for(v in item)
			{
				if(col == v)
				{
					isFiled = true;
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : item[v],
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue||item[v]);
					tplCol = tplCol.replace("{text}",j==0 ? indents + this.extendIcon + span : span);
					tplCol = tplCol.replace("{width}" , this.dynamicColWidth[j]+"px");
					tplCol = tplCol.replace("{field}",v);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;
				}
			}
			if(!isFiled)
			{
					span = tplSpan;
					colValue = formatter&&formatter.call(this,{
						col : columns[j].text,
						rows : this.options.data,
						data : this.options.data,
						row : this.options.data[i],
						index : i
					});
					span = span.replace("{text}",colValue||columns[j].text||"");
					tplCol = tplCol.replace("{text}",j==0 ? indents + this.extendIcon + span : span);
					tplCol = tplCol.replace("{width}" , this.dynamicColWidth[j]+"px");
					tplCol = tplCol.replace("{field}",columns[j].field);
					tplCol = tplCol.replace("{treeGrid-col-n}","treeGrid-col-"+j);
					tplCols = tplCols + tplCol;				
			}
		}
		tplRow = tplRow.replace("{cols}",tplCols);
		tplRow = tplRow.replace("{index}",i);
		tplRow = tplRow.replace("{level}",indentLen);
		tplRow = tplRow.replace("{treeGrid-row-n}","treeGrid-row-"+i);

		tr = document.createElement("tr");
		tr.className = "treeGrid-row";
		tr.setAttribute("index",i);
		tr.setAttribute("level",indentLen);
		tr.innerHTML = tplRow;
		
		var node = this.dom_curRow.nextSibling;
		if(node!=null)
		{
			node.parentNode.insertBefore(tr,node);
		}
		else
		{
			this.dom_curRow.parentNode.appendChild(tr);
		}		
	}
	
	this.hideMask();
};

/*
type:外部接口
function:动态添加列
*/
TreeGrid.prototype.addCell = function(options){
	/*
	options = {
		text : "",
		field : "",
		title : ""
	}
	*/

	if(options==undefined)
	{
		return;
	}

	this.options.columns.push(options);

	var tdContentTpl ='<div class="treeGrid-col-content"><span class="treeGrid-col-text">{text}</span></div>';
	var tdContent;
	var table = this.options.container.querySelector(".treeGrid");
	var trs = table.getElementsByTagName("tr");
	Array.prototype.forEach.call(trs, function(tr) {
		var thead = tr.parentNode.nodeName;
		var td;
		var tdLen;/*当前表格tr有多少个td*/
		if(tr.className=="treeGrid-row-tree")
		{
			tdLen = tr.querySelectorAll("td").length;
			tr.querySelector("td").setAttribute("colspan",tdLen);
			return;
		}
		td = tr.insertCell();
		if(thead == "THEAD")
		{
			tdContent = tdContentTpl.replace("{text}",options.title||"&nbsp;");
		}
		else
		{
			tdContent = tdContentTpl.replace("{text}",options.text||"&nbsp;");
		}
	    td.innerHTML = tdContent;
	    td.style.width = options.width;
	    td.setAttribute("field",options.field||"newCell");
	    td.className = "treeGrid-col treeGrid-col-add";
	});
}


